/*
 *  mmap() - POSIX 1003.1b 6.3.1 - map pages of memory
 *
 *  COPYRIGHT (c) 2010.
 *  Chris Johns (chrisj@rtems.org)
 *
 *  The license and distribution terms for this file may be
 *  found in the file LICENSE in this distribution or at
 *  http://www.rtems.com/license/LICENSE.
 *
 *  $Id$
 */

#if HAVE_CONFIG_H
#include "config.h"
#endif

#include <rtems.h>
#include <errno.h>
#include <stdlib.h>
#include <rtems/posix/mman.h>
#include <rtems/posix/mmap-internal.h>

int munmap(
  void *addr, size_t len
)
{
  rtems_memory_protection_domain *mapping = &mmap_mappings;
  rtems_memory_protection_entry  *current;
  
  /*
   * Clear errno.
   */
  errno = 0;

  /*
   * Length cannot be 0.
   */
  if ( len == 0 ) {
    errno = EINVAL;
    return -1;
  }

  /*
   * Obtain the mmap lock. Sets errno on failure.
   */
  if ( !mmap_mappings_lock_obtain( ))
    return -1;

  current =  (rtems_memory_protection_entry* )rtems_chain_first (&mapping->active_mpe_chain);
  while ( !rtems_chain_is_tail( &mapping->active_mpe_chain, &current->node) ){
    /*
     * If the map is fixed see if this address is already mapped. At this
     * point in time if there is an overlap in the mappings we return an
     * error.
     */
     
    if ( ( addr >= current->region.base ) &&
         ( addr < ( current->region.base + current->region.bounds)) ) {
      rtems_chain_extract_unprotected( &current->node );

      rtems_memory_protection_uninstall_entry(current);

      /* TODO:
       * for the delete entry block the attribute should be changed 
       * default access attribute 
       * so update the related cache tlb and pagetable entry? */
//      current->permissions = mapping->default_permissions;
//      rtems_memory_protection_install_entry(current);   
      
      if (( current->permissions& RTEMS_MEMORY_PROTECTION_MAP_FIXED ) != RTEMS_MEMORY_PROTECTION_MAP_FIXED ) {
        free( current->region.base  );
      }
      current->region.bounds = 0;
      current->region.base = 0;
      current->permissions = RTEMS_MEMORY_PROTECTION_NO_PERMISSION;

      rtems_chain_append_unprotected( &mapping->idle_mpe_chain, &current->node);
      break;
    }
    current = (rtems_memory_protection_entry* )rtems_chain_next(&current->node);
  }

  mmap_mappings_lock_release( );
  return 0;
}
